﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mvvm.Models;
using MvvM.Services;

namespace Mvvm.Services
{
    public class EmotionReportService
    {
        private readonly ChatDataProcessedStorage _chatDataProcessedStorage;
        
        // 定义情感类别及其对应的数量统计字典
        public Dictionary<string, int> _emotionCounts = new Dictionary<string, int>()
        {
            { "积极", 0 }, { "中性", 0 }, { "消极", 0 },
            { "喜爱", 0 }, { "愉快", 0 }, { "正常", 0 }, { "愤怒", 0 }, { "厌恶", 0 }, { "恐惧", 0 }, { "悲伤", 0 }
        };

        // 分角色统计情感数量的字典，键为用户名，值为该用户的情感数量字典
        public Dictionary<string, Dictionary<string, int>> _userEmotionCounts = new Dictionary<string, Dictionary<string, int>>();

        // 用于情绪传染分析：存储每个用户受到其他用户情绪影响的情况
        private Dictionary<string, Dictionary<string, Dictionary<string, int>>> _emotionInfluence = new Dictionary<string, Dictionary<string, Dictionary<string, int>>>();

        // 用于情绪回应模式分析：存储每个用户对其他用户不同情绪的回应情况
        private Dictionary<string, Dictionary<string, Dictionary<string, int>>> _emotionResponse = new Dictionary<string, Dictionary<string, Dictionary<string, int>>>();

        public EmotionReportService(ChatDataProcessedStorage chatDataProcessedStorage)
        {
            _chatDataProcessedStorage = chatDataProcessedStorage;
        }
        
        // 统计聊天数据中的情感数量
        public void AnalyzeEmotionData(List<ChatData> chatDataList)
        {
            foreach (var chatData in chatDataList)
            {
                // 统计总体情感数量
                if (chatData.Emotion == "optimistic")
                {
                    _emotionCounts["积极"]++;
                }
                else if (chatData.Emotion == "neutral")
                {
                    _emotionCounts["中性"]++;
                }
                else if (chatData.Emotion == "pessimistic")
                {
                    _emotionCounts["消极"]++;
                }

                // 统计具体情感词数量
                if (chatData.EmotionTone == "like")
                {
                    _emotionCounts["喜爱"]++;
                }
                else if (chatData.EmotionTone == "happy")
                {
                    _emotionCounts["愉快"]++;
                }
                else if (chatData.EmotionTone == "normal")
                {
                    _emotionCounts["正常"]++;
                }
                else if (chatData.EmotionTone == "angry")
                {
                    _emotionCounts["愤怒"]++;
                }
                else if (chatData.EmotionTone == "disgusting")
                {
                    _emotionCounts["厌恶"]++;
                }
                else if (chatData.EmotionTone == "fearful")
                {
                    _emotionCounts["恐惧"]++;
                }
                else if (chatData.EmotionTone == "sad")
                {
                    _emotionCounts["悲伤"]++;
                }

                // 分角色统计情感数量
                if (!_userEmotionCounts.ContainsKey(chatData.Username))
                {
                    _userEmotionCounts[chatData.Username] = new Dictionary<string, int>(_emotionCounts);
                }

                if (chatData.Emotion == "optimistic")
                {
                    _userEmotionCounts[chatData.Username]["积极"]++;
                }
                else if (chatData.Emotion == "neutral")
                {
                    _userEmotionCounts[chatData.Username]["中性"]++;
                }
                else if (chatData.Emotion == "pessimistic")
                {
                    _userEmotionCounts[chatData.Username]["消极"]++;
                }

                if (chatData.EmotionTone == "like")
                {
                    _userEmotionCounts[chatData.Username]["喜爱"]++;
                }
                else if (chatData.EmotionTone == "happy")
                {
                    _userEmotionCounts[chatData.Username]["愉快"]++;
                }
                else if (chatData.EmotionTone == "normal")
                {
                    _userEmotionCounts[chatData.Username]["正常"]++;
                }
                else if (chatData.EmotionTone == "angry")
                {
                    _userEmotionCounts[chatData.Username]["愤怒"]++;
                }
                else if (chatData.EmotionTone == "disgusting")
                {
                    _userEmotionCounts[chatData.Username]["厌恶"]++;
                }
                else if (chatData.EmotionTone == "fearful")
                {
                    _userEmotionCounts[chatData.Username]["恐惧"]++;
                }
                else if (chatData.EmotionTone == "sad")
                {
                    _userEmotionCounts[chatData.Username]["悲伤"]++;
                }

                // 情绪传染分析
                AnalyzeEmotionInfluence(chatData, chatDataList);

                // 情绪回应模式分析
                AnalyzeEmotionResponse(chatData, chatDataList);
            }
        }

        // 情绪传染分析方法
        private void AnalyzeEmotionInfluence(ChatData chatData, List<ChatData> chatDataList)
        {
            string sender = chatData.Username;
            string currentEmotion = chatData.EmotionTone;
            // 定义强烈情绪列表
            string[] strongEmotions = { "angry", "disgusting", "fearful", "sad", "like", "happy" };
            if (strongEmotions.Contains(currentEmotion))
            {
                // 遍历其他用户的后续消息（这里简单假设后续5条消息内可能受影响，可根据实际情况调整）
                int influenceRange = 5;
                for (int i = 1; i <= influenceRange; i++)
                {
                    int index = chatDataList.IndexOf(chatData) + i;
                    if (index < chatDataList.Count)
                    {
                        var nextChatData = chatDataList[index];
                        if (nextChatData.Username!= sender)
                        {
                            // 初始化数据结构
                            if (!_emotionInfluence.ContainsKey(sender))
                            {
                                _emotionInfluence[sender] = new Dictionary<string, Dictionary<string, int>>();
                            }
                            if (!_emotionInfluence[sender].ContainsKey(nextChatData.Username))
                            {
                                _emotionInfluence[sender][nextChatData.Username] = new Dictionary<string, int>();
                            }
                            if (!_emotionInfluence[sender][nextChatData.Username].ContainsKey(currentEmotion))
                            {
                                _emotionInfluence[sender][nextChatData.Username][currentEmotion] = 0;
                            }

                            // 统计情绪传染情况
                            _emotionInfluence[sender][nextChatData.Username][currentEmotion]++;
                        }
                    }
                }
            }
        }

        // 情绪回应模式分析方法
        private void AnalyzeEmotionResponse(ChatData chatData, List<ChatData> chatDataList)
        {
            string sender = chatData.Username;
            string currentEmotion = chatData.EmotionTone;

            // 查找下一条其他用户的消息
            int index = chatDataList.IndexOf(chatData) + 1;
            while (index < chatDataList.Count)
            {
                var nextChatData = chatDataList[index];
                if (nextChatData.Username!= sender)
                {
                    // 初始化数据结构
                    if (!_emotionResponse.ContainsKey(sender))
                    {
                        _emotionResponse[sender] = new Dictionary<string, Dictionary<string, int>>();
                    }
                    if (!_emotionResponse[sender].ContainsKey(nextChatData.Username))
                    {
                        _emotionResponse[sender][nextChatData.Username] = new Dictionary<string, int>();
                    }
                    if (!_emotionResponse[sender][nextChatData.Username].ContainsKey(currentEmotion))
                    {
                        _emotionResponse[sender][nextChatData.Username][currentEmotion] = 0;
                    }

                    // 统计情绪回应情况
                    _emotionResponse[sender][nextChatData.Username][currentEmotion]++;
                    break;
                }
                index++;
            }
        }

        // 生成情感报告字符串
        public string GenerateEmotionReport()
        {
        // 生成情感报告字符串并填充 ChatProcessedData 实例
        // public ChatProcessedData GenerateEmotionReport()
        // {
            var chatProcessedData = new ChatProcessedData();

            // 总聊天消息条数
            chatProcessedData.TotalChatCount = _emotionCounts.Values.Sum();

            // 积极消息数量
            chatProcessedData.PositiveMessageCount = _emotionCounts["积极"];
            // 中性消息数量
            chatProcessedData.NeutralMessageCount = _emotionCounts["中性"];
            // 消极消息数量
            chatProcessedData.NegativeMessageCount = _emotionCounts["消极"];

            // 喜爱情绪消息数量
            chatProcessedData.LoveMessageCount = _emotionCounts["喜爱"];
            // 愉快情绪消息数量
            chatProcessedData.HappyMessageCount = _emotionCounts["愉快"];
            // 正常情绪消息数量
            chatProcessedData.NormalMessageCount = _emotionCounts["正常"];
            // 愤怒情绪消息数量
            chatProcessedData.AngryMessageCount = _emotionCounts["愤怒"];
            // 厌恶情绪消息数量
            chatProcessedData.DisgustMessageCount = _emotionCounts["厌恶"];
            // 恐惧情绪消息数量
            chatProcessedData.FearMessageCount = _emotionCounts["恐惧"];
            // 悲伤情绪消息数量
            chatProcessedData.SadMessageCount = _emotionCounts["悲伤"];

            // 用户 1 相关情感数量
            string user1 = "";
            string user2 = "";
            int index = 0;
            foreach (var username in _userEmotionCounts.Keys)
            {
                if (index == 0)
                {
                    user1 = username;
                }
                else if (index == 1)
                {
                    user2 = username;
                }
                index++;
            }

            if (!string.IsNullOrEmpty(user1))
            {
                chatProcessedData.User1PositiveMessageCount = _userEmotionCounts[user1]["积极"];
                chatProcessedData.User1NeutralMessageCount = _userEmotionCounts[user1]["中性"];
                chatProcessedData.User1NegativeMessageCount = _userEmotionCounts[user1]["消极"];
                chatProcessedData.User1LoveMessageCount = _userEmotionCounts[user1]["喜爱"];
                chatProcessedData.User1HappyMessageCount = _userEmotionCounts[user1]["愉快"];
                chatProcessedData.User1NormalMessageCount = _userEmotionCounts[user1]["正常"];
                chatProcessedData.User1AngryMessageCount = _userEmotionCounts[user1]["愤怒"];
                chatProcessedData.User1DisgustMessageCount = _userEmotionCounts[user1]["厌恶"];
                chatProcessedData.User1FearMessageCount = _userEmotionCounts[user1]["恐惧"];
                chatProcessedData.User1SadMessageCount = _userEmotionCounts[user1]["悲伤"];
            }
            else
            {
                chatProcessedData.User1PositiveMessageCount = 0;
                chatProcessedData.User1NeutralMessageCount = 0;
                chatProcessedData.User1NegativeMessageCount = 0;
                chatProcessedData.User1LoveMessageCount = 0;
                chatProcessedData.User1HappyMessageCount = 0;
                chatProcessedData.User1NormalMessageCount = 0;
                chatProcessedData.User1AngryMessageCount = 0;
                chatProcessedData.User1DisgustMessageCount = 0;
                chatProcessedData.User1FearMessageCount = 0;
                chatProcessedData.User1SadMessageCount = 0;
            }

            // 用户 2 相关情感数量
            if (!string.IsNullOrEmpty(user2))
            {
                chatProcessedData.User2PositiveMessageCount = _userEmotionCounts[user2]["积极"];
                chatProcessedData.User2NeutralMessageCount = _userEmotionCounts[user2]["中性"];
                chatProcessedData.User2NegativeMessageCount = _userEmotionCounts[user2]["消极"];
                chatProcessedData.User2LoveMessageCount = _userEmotionCounts[user2]["喜爱"];
                chatProcessedData.User2HappyMessageCount = _userEmotionCounts[user2]["愉快"];
                chatProcessedData.User2NormalMessageCount = _userEmotionCounts[user2]["正常"];
                chatProcessedData.User2AngryMessageCount = _userEmotionCounts[user2]["愤怒"];
                chatProcessedData.User2DisgustMessageCount = _userEmotionCounts[user2]["厌恶"];
                chatProcessedData.User2FearMessageCount = _userEmotionCounts[user2]["恐惧"];
                chatProcessedData.User2SadMessageCount = _userEmotionCounts[user2]["悲伤"];
            }
            else
            {
                chatProcessedData.User2PositiveMessageCount = 0;
                chatProcessedData.User2NeutralMessageCount = 0;
                chatProcessedData.User2NegativeMessageCount = 0;
                chatProcessedData.User2LoveMessageCount = 0;
                chatProcessedData.User2HappyMessageCount = 0;
                chatProcessedData.User2NormalMessageCount = 0;
                chatProcessedData.User2AngryMessageCount = 0;
                chatProcessedData.User2DisgustMessageCount = 0;
                chatProcessedData.User2FearMessageCount = 0;
                chatProcessedData.User2SadMessageCount = 0;
            }
            
            StringBuilder reportBuilder = new StringBuilder();

            reportBuilder.AppendLine("以下是我们为你生成的情感报告：");
            if (_emotionCounts["积极"] > 0)
            {
                reportBuilder.AppendLine($"在我们分析的数据中，积极消息有 {_emotionCounts["积极"]} 条。这表明在你们的交流中，有不少令人感到开心和正面的时刻呢。");
            }
            else
            {
                reportBuilder.AppendLine("在我们分析的数据中，没有发现积极消息，或许可以尝试多分享一些开心的事情哦。");
            }
            if (_emotionCounts["中性"] > 0)
            {
                reportBuilder.AppendLine($"中性消息的数量是 {_emotionCounts["中性"]} 条，这些消息可能是比较客观或者日常的交流内容。");
            }
            else
            {
                reportBuilder.AppendLine("在我们分析的数据中，没有发现中性消息，交流内容可能都比较带有情感倾向哦。");
            }
            if (_emotionCounts["消极"] > 0)
            {
                reportBuilder.AppendLine($"消极消息有 {_emotionCounts["消极"]} 条，希望这些消极情绪不会给你们带来太大的困扰哦。");
            }
            else
            {
                reportBuilder.AppendLine("在我们分析的数据中，没有发现消极消息，这很棒，说明交流氛围比较积极呢！");
            }

            // 喜爱情绪
            if (_emotionCounts["喜爱"] > 0)
            {
                reportBuilder.AppendLine($"我们还发现喜爱情绪的消息有 {_emotionCounts["喜爱"]} 条，这真的很棒，说明你们之间有着深厚的感情呢。");
            }

            // 愉快情绪
            if (_emotionCounts["愉快"] > 0)
            {
                reportBuilder.AppendLine($"愉快情绪的消息数量是 {_emotionCounts["愉快"]} 条，这些时刻一定充满了欢声笑语。");
            }

            // 正常情绪
            if (_emotionCounts["正常"] > 0)
            {
                reportBuilder.AppendLine($"正常情绪消息有 {_emotionCounts["正常"]} 条，这是交流中的常态啦。");
            }

            // 愤怒情绪
            if (_emotionCounts["愤怒"] > 0)
            {
                reportBuilder.AppendLine($"愤怒情绪的消息有 {_emotionCounts["愤怒"]} 条，遇到这种情况的时候，要好好沟通，避免矛盾升级呀。");
            }

            // 厌恶情绪
            if (_emotionCounts["厌恶"] > 0)
            {
                reportBuilder.AppendLine($"厌恶情绪消息数量为 {_emotionCounts["厌恶"]} 条，希望这种情绪不要频繁出现哦。");
            }

            // 恐惧情绪
            if (_emotionCounts["恐惧"] > 0)
            {
                reportBuilder.AppendLine($"恐惧情绪消息有 {_emotionCounts["恐惧"]} 条，是不是有什么事情让你们感到不安了呢？");
            }

            // 悲伤情绪
            if (_emotionCounts["悲伤"] > 0)
            {
                reportBuilder.AppendLine($"悲伤情绪消息数量是 {_emotionCounts["悲伤"]} 条，希望你们能相互安慰，度过那些难过的时刻。");
            }

            reportBuilder.AppendLine("\n分角色情感统计：");
            foreach (var user in _userEmotionCounts.Keys)
            {
                reportBuilder.AppendLine($"现在来看看 {user} 的情感统计：");
                if (_userEmotionCounts[user]["积极"] > 0)
                {
                    reportBuilder.AppendLine($"对于 {user} 来说，积极消息有 {_userEmotionCounts[user]["积极"]} 条，这反映了他/她在交流中带来了不少正面能量。");
                }
                if (_userEmotionCounts[user]["中性"] > 0)
                {
                    reportBuilder.AppendLine($"中性消息有 {_userEmotionCounts[user]["中性"]} 条，这些可能是他/她比较平常的表述。");
                }
                if (_userEmotionCounts[user]["消极"] > 0)
                {
                    reportBuilder.AppendLine($"消极消息数量是 {_userEmotionCounts[user]["消极"]} 条，看看是不是有什么原因导致了这些消极情绪呢？");
                }

                // 用户的喜爱情绪消息
                if (_userEmotionCounts[user]["喜爱"] > 0)
                {
                    reportBuilder.AppendLine($"喜爱情绪消息有 {_userEmotionCounts[user]["喜爱"]} 条，这体现了他/她对某些事物或人的喜爱之情。");
                }

                // 用户的愉快情绪消息
                if (_userEmotionCounts[user]["愉快"] > 0)
                {
                    reportBuilder.AppendLine($"愉快情绪消息数量为 {_userEmotionCounts[user]["愉快"]} 条，说明他/她也有不少开心的瞬间呢。");
                }

                // 用户的正常情绪消息
                if (_userEmotionCounts[user]["正常"] > 0)
                {
                    reportBuilder.AppendLine($"正常情绪消息有 {_userEmotionCounts[user]["正常"]} 条，这是他/她交流中的日常状态。");
                }

                // 用户的愤怒情绪消息
                if (_userEmotionCounts[user]["愤怒"] > 0)
                {
                    reportBuilder.AppendLine($"愤怒情绪消息数量是 {_userEmotionCounts[user]["愤怒"]} 条，可能他/她在某些情况下会比较激动。");
                }

                // 用户的厌恶情绪消息
                if (_userEmotionCounts[user]["厌恶"] > 0)
                {
                    reportBuilder.AppendLine($"厌恶情绪消息有 {_userEmotionCounts[user]["厌恶"]} 条，这种情绪出现的时候，要留意一下背后的原因哦。");
                }

                // 用户的恐惧情绪消息
                if (_userEmotionCounts[user]["恐惧"] > 0)
                {
                    reportBuilder.AppendLine($"恐惧情绪消息数量为 {_userEmotionCounts[user]["恐惧"]} 条，是不是有什么让他/她害怕的事情呢？");
                }

                // 用户的悲伤情绪消息
                if (_userEmotionCounts[user]["悲伤"] > 0)
                {
                    reportBuilder.AppendLine($"悲伤情绪消息有 {_userEmotionCounts[user]["悲伤"]} 条，希望他/她在感到难过的时候，能得到关心和支持。");
                }
            }

            // 情绪传染分析结果
            reportBuilder.AppendLine("\n情绪传染分析：");
            foreach (var sender in _emotionInfluence.Keys)
            {
                foreach (var receiver in _emotionInfluence[sender].Keys)
                {
                    foreach (var emotion in _emotionInfluence[sender][receiver].Keys)
                    {
                        reportBuilder.AppendLine($"{GetChineseEmotion(emotion)}情绪从{sender}对{receiver}产生影响的次数：{_emotionInfluence[sender][receiver][emotion]}");
                    }
                }
            }

            // 情绪回应模式分析结果
            reportBuilder.AppendLine("\n情绪回应模式分析：");
            foreach (var sender in _emotionResponse.Keys)
            {
                foreach (var receiver in _emotionResponse[sender].Keys)
                {
                    foreach (var emotion in _emotionResponse[sender][receiver].Keys)
                    {
                        reportBuilder.AppendLine($"{GetChineseEmotion(emotion)}情绪由{sender}发出后，{receiver}的回应次数：{_emotionResponse[sender][receiver][emotion]}");
                    }
                }
            }

            // 根据情感统计数据给出总体情绪判断
            string overallEmotionJudgment = "";
            int totalPositive = 0, totalNegative = 0, totalNeutral = 0;
            foreach (var userEmotions in _userEmotionCounts.Values)
            {
                totalPositive += userEmotions["积极"];
                totalNegative += userEmotions["消极"];
                totalNeutral += userEmotions["中性"];
            }

            if (totalPositive > totalNegative && totalPositive > totalNeutral)
            {
                overallEmotionJudgment = "整体来看，你们的交流情绪较为积极乐观，这是非常好的呢！";
            }
            else if (totalNegative > totalPositive && totalNegative > totalNeutral)
            {
                overallEmotionJudgment = "从整体情绪上看，可能有些消极负面的情况，要注意调整哦。";
            }
            else
            {
                overallEmotionJudgment = "总体来说，你们的交流情绪相对比较中性。";
            }
            reportBuilder.AppendLine($"\n总体情绪判断：{overallEmotionJudgment}");

            return reportBuilder.ToString();
        }

        // 将英文情感标签转换为中文的方法
        private string GetChineseEmotion(string emotion)
        {
            switch (emotion)
            {
                case "like":
                    return "喜爱";
                case "happy":
                    return "愉快";
                case "normal":
                    return "正常";
                case "angry":
                    return "愤怒";
                case "disgusting":
                    return "厌恶";
                case "fearful":
                    return "恐惧";
                case "sad":
                    return "悲伤";
                default:
                    return emotion;
            }
        }

        // 调用大模型对情感统计结果进行分析并获取建议
        public async Task<string> GetSuggestionsFromAI(List<ChatData> chatDataList)
        {
            var aiService = new EmotionAIService();
            var result = await aiService.AnalyzeEmotionDataAndGetSuggestions(chatDataList);
            return result;
        }
    }
}